//--------------------------------------------------------//
//Filename:routers.js
//Create Time:2020年02月06日 星期四 23时48分16秒
//Description:
const path = require('path');
const KoaBody = require('koa-body');
const Router  = require('koa-router');
const excutedb = require('../handlers/excutedb');
const jwt = require('jsonwebtoken');
const koajwt = require('koa-jwt');
const config = require('../config.js');

const auth = async function(ctx,next){
	if(ctx.url.indexOf('api') !== -1)	
		ctx.throw(401,'鉴权失败');
	console.log(ctx);	
	await next();
};

const auth2 = async function(ctx,next){
	console.log(Date.now());	
	await next();
};

const auth_redirect = async function(ctx,next){
	console.log('ctx.response.redirect(/home)');
	ctx.response.redirect('/');
}

const normal_router = new Router();
const api_router = new Router({prefix:'/api'});

const ttt = koajwt({secret:config.SECRETKEY});
normal_router.get('/',ttt,async (ctx,next)=>{
	console.log(config.SECRETKEY);
	ctx.response.body = '<h1>Home Page</h1>';
});

normal_router.get('/hello/:name/:age',ttt,async (ctx,next)=>{
	ctx.verifyParams({
		name:{type:'string',required:true},
		age:{type:'string',required:true}
	});
	let name = ctx.params.name;
	let age = ctx.params.age;
	ctx.response.body={nae:'ok'};
	//ctx.response.body = `<h1>Hello,${name}:${age}</h1>`;
});

normal_router.get('/tuserinfo',async(ctx,next)=>{
	console.log(ctx);
	//let token = ctx.request.header.authorization;
	ctx.response.body = {name:'ok'};
	//let token = ctx.request.header.authorization;
	//console.log(token);
	//ctx.response.body = {
//		        token:token,
//		        user:ctx.state.user
//	   };
    //使用jwt-simple自行解析数据
  // let payload = jwt.decode(token.split(' ')[1],config.SECRETKEY);
  // console.log(payload);
});

const authtoken = async (ctx,next)=>{
	let token = ctx.request.header.authorization;
	if(!token)
		ctx.throw(401,'not token');
	let st = token.split(' ')[1];
	console.log(st);
	try{
		let userinfo =jwt.verify(st,config.SECRETKEY);
		console.log('auth ok');
		ctx.state.user = userinfo;
		await next();
		//ctx.response.body={msg:'OK'};
	}catch(err){
		console.log(err);
		ctx.throw(401,'没有权限');
	}
};

const authjwt = koajwt({secret:config.SECRETKEY});

normal_router.post('/postdata',async (ctx,next)=>{
	console.log(ctx.request.body);
	console.log('-------------');
	console.log(ctx.state.user);
	ctx.response.body=ctx.request.body;
});


normal_router.post('/postdata2',async (ctx,next)=>{
	console.log(ctx.request.body);
	ctx.response.body=ctx.request.body;
});

normal_router.post('/postdatavalid',async (ctx,next)=>{
	ctx.verifyParams({
		name:{type:'string',required:true},
		age:{type:'number',max:100,requied:true},
		gender:["A","B"]
	});
	console.log(ctx.request.body);
	ctx.response.body=ctx.request.body;
});

api_router.post('/addnewword',excutedb.addnewword);

//查询单词，返回一个带词根的对象
normal_router.get('/query/:word',excutedb.queryword);

normal_router.put('/putquery/:word',excutedb.queryword);
normal_router.delete('/putquery/:word',excutedb.queryword);

//查询词根
normal_router.get('/queryetyma/:etyma',excutedb.queryetyma);


normal_router.get('/gettoken',async(ctx,next)=>{
	let token=jwt.sign({name:'UserToken',msg:'success'},"key");
	ctx.response.body = {token:token,msg:'success'};
});

normal_router.options('/options',async(ctx,next)=>{
	ctx.response.body = ctx.request; 
});

normal_router.get('/login',async(ctx,next)=>{
	ctx.response.body = {login:true}; 
});

normal_router.post('/load',async(ctx,next)=>{
	console.log(ctx.request);
	const file = ctx.request.files.file;
	let basename = path.basename(file.path);
	let baseurl = ctx.origin;
	ctx.body = {url:`${baseurl}/uploads/${basename}`};
});

//上传
normal_router.post('/upload',async(ctx,next)=>{
	console.log(ctx.request);
	const file = ctx.request.files.file;
	let basename = path.basename(file.path);
	let baseurl = ctx.origin;
	ctx.body = {url:`${baseurl}/uploads/${basename}`};
});

//登录
normal_router.post('/trylogin',async(ctx,next)=>{
	let username = ctx.request.body["username"];
	let userpassword = ctx.request.body.userpassword;
	let resobj = await excutedb.findmanageronly({username:username,userpassword:userpassword});
	if(resobj.statuscode === 200){
		let tokenobj = {username:username,uid:resobj.data.uid,powermask:resobj.data.powermask};
		let token = jwt.sign(tokenobj,config.SECRETKEY);
		ctx.state.user = token;
		let obj ={token:token,username:username,powermask:tokenobj.powermask,userid:tokenobj.uid,message:'登录成功',statuscode:200};	
		ctx.response.body=obj;
	}
	else{
		ctx.response.body={message:'登录失败,用户名或密码错误',statuscode:404};	
	}
});

normal_router.get('/checktoken',async(ctx,next)=>{
	console.log("authorization:"+ctx.request.header.authorization);
	if(ctx.request.header.authorization){
		let st = ctx.request.header.authorization.split(' ')[1]
		let obj = jwt.verify(st,config.SECRETKEY);
		console.log(obj);
		ctx.response.body = obj;
	}else{
		ctx.response.body = {message:'exists no token',codestatus:408};	
	}
});

//设置管理员
normal_router.put('/addmanager',excutedb.addmanager);
//查找管理员
normal_router.post('/findmanager',excutedb.findmanager);

api_router.get('/testuser',auth,async (ctx,next)=>{
	ctx.body='测试 api_router';
});

api_router.get('/finduser/:uid',auth,async (ctx,next)=>{
	let uid = ctx.params.uid;
	ctx.body="ctx.params.uid:"+uid;
});

api_router.get('/testerror',async (ctx,next)=>{
	ctx.throw('403');
});

//单词增删改查
api_router.get('/getwords/:skip/:limit',excutedb.getwords);
api_router.get('/searchwords/:letters',excutedb.searchwords);
api_router.get('/deleteword/:wordid',excutedb.deleteword);
api_router.post('/updateword',excutedb.updateword);
//增加学习次数
api_router.get('/addclasstime/:id',excutedb.addclasstime);

//获取词根列表
api_router.get('/getetymas/:skip/:limit',excutedb.getetymas);
//更新词根
api_router.post('/updateetyma',excutedb.updateetyma);
//删除词根
api_router.get('/deleteetyma/:etymaid',excutedb.deleteetyma);
//添加词根
api_router.post('/addnewetyma',excutedb.addnewetyma);



//供app 调用，挂接路由
module.exports = function(app){
	app.use(normal_router.routes());
	app.use(api_router.routes());
	app.use(normal_router.allowedMethods());
	app.use(api_router.allowedMethods());
}
